package com.dongdongshop.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
       //设置会话管理
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String,String> filterMap = new LinkedHashMap<>();
         filterMap.put("/getAdminInfoByName","anon");
        filterMap.put("/toLogin","anon");
        filterMap.put("/login","anon");
        filterMap.put("/js/**", "anon");
        filterMap.put("/bootstrap/**", "anon");
        filterMap.put("/css/**", "anon");
        filterMap.put("/img/**", "anon");
        filterMap.put("/plugins/**", "anon");
        filterMap.put("/code/**", "anon");


        filterMap.put("/auth/logout", "logout");

        filterMap.put("/**", "authc");

        //修改登录跳转地址
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //将map存到shiro的过滤器链中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired AdminRealm adminRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(getAdminRealm());
        return securityManager;
    }

    @Bean
    public AdminRealm getAdminRealm(){
        AdminRealm adminRealm = new AdminRealm();
        //设置加密方式
        adminRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return adminRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式,sha-1 sha-2
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数 1234 - > xxxabc -> yyydef
        hashedCredentialsMatcher.setHashIterations(3);
        //加密的编码
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }
}
